$(document).ready(function(){
	//顶部用户登陆后显示隐藏下拉菜单
	$("#user-id").click(function(){
		if($("#showBox").is(":hidden")){
			$("#showBox").show();
			$(this).removeClass().addClass("down");
		}else{
			$("#showBox").hide();
			$(this).removeClass().addClass("up");
		}
	});
	//首页收藏功能. 添加收藏
	$(".hover-add-favor").click(function(){
		//判断用户是否已登录,如果未登录弹出登录
		if(show_login_box()){
			return false;
		}
		var add_favor_button=$(this);
		var shop_id=$("#shop-"+ $(this).attr("rel"));
		$.ajax({
            type: "post",
            url: "include/zy_function.php",
			data:{method:"addFavoShop",shop_id:$(this).attr("rel")},
            dataType: "json",
            success: function(){
            	shop_id.find(".favor-book .favor-icon").show();
            	shop_id.addClass("has-favor-icon");
        		add_favor_button.hide();
        		add_favor_button.next().show();
            }
         });
	});
	//首页收藏功能. 取消收藏
	$(".hover-un-favor").click(function(){
		//判断用户是否已登录,如果未登录弹出登录
		if(show_login_box()){
			return false;
		}
		 var un_favor_button=$(this);
		 var shop_id=$("#shop-"+ $(this).attr("rel"));
         $.ajax({
             type: "post",
             url: "include/zy_function.php",
 			data:{method:"unFavoShop",shop_id:$(this).attr("rel")},
             dataType: "json",
             success: function(){
            	 shop_id.find(".favor-book .favor-icon").hide();
        		 shop_id.removeClass("has-favor-icon");
                 un_favor_button.hide();
                 un_favor_button.prev().show();
             }
          });
	});

	//首页鼠标移到店铺上显示详细信息
	var i=null;
	$(".promoted-restaurants .restaurant-block, .more-restaurants .restaurant-block").live("mouseenter",
	function() {
	    var s = $(this);
	    $(this).find(".status-desc").hide();
	    if ($(this).hasClass("has-favor-icon")) {
	    	$(this).find(".hover-un-favor").show();
	    } else {
	    	$(this).find(".hover-add-favor").show();
	    }
	    i = setTimeout(function() {
	        var x = s.offset().left + s.width() + 5;
	        var w = s.offset().top - 10;
	        if (x + 360 > $(window).width()) {
	            x = s.offset().left - 10 - 360;
	            $("#copy_dlg_restaurant").addClass("left").removeClass("right").css({
	                left: x,
	                top: w
	            }).show();
	        } else {
	            $("#copy_dlg_restaurant").addClass("right").removeClass("left").css({
	                left: x,
	                top: w
	            }).show();
	        }
	        $("#copy_dlg_restaurant .detail").html(s.find(".line-hover-dlg").html());
	    },
	    360);
	}).live("mouseleave",
	function() {
	    $(this).find(".status-desc").show();
	    $(this).find(".hover-un-favor").hide();
	    $(this).find(".hover-add-favor").hide();
	    clearTimeout(i);
	    $("#copy_dlg_restaurant .detail").html("");
	    $("#copy_dlg_restaurant").hide();
	});
	//关闭提示框
    $(".btn.complete,.close,.cancel,#cancel-button").click(function() {
    	$(".modal").modal("hide");
    });

	//回到顶部
	$('#back-to-top').click(function() {
		$("body, html").animate({ scrollTop: 0 }, 500);
	});
		
	$(window).resize(function(){
		$(window).height();
	});
	$(window).scroll(function(){
		//控制bottom-cart位置
		if($(".right-fold").offset()!=null){
			var dddd=$(".right-fold");
			var cccc=$(window).height();
			var bbbb=$(".right-fold").offset().top;
			var l=dddd.height();
			var i=bbbb+l;
			var m=$("#bottom-cart");
			var k=$(window).scrollTop();
			var j=cccc+k-i-1;
			if(j>0){
				m.css({bottom:j});
			}else{
				m.css({bottom:0});
			}
		}
		//控制回到顶端按钮是否显示
		 if ($(window).scrollTop()>50) {
	        	$("#back-to-top").show();
	        } else {
	        	$("#back-to-top").hide();
	        }
	});
	//控制底部购物车是否显示.
	$(".line-brief").click(function(){
		 if ($(".line-detail").is(":visible")) {
	         close();
	     } else {
	        openCart();
	        
	     }
	});
	
	//买单按钮
	$(".cart-btn").click(function(){
			if($("#cart-details tr").size()>1){
				window.location.href="check_out.php";
			}else{
				alert("请先选择您需要的美食!");
			}
			return false;
	});
	//是否已经存在一辆购物车.如果存在提示清除当前购物车
	if($("#showOtherCarNotice").html()=="false"){
		showOtherCarNotice();
	}
	$("#add-favor").click(function(){
		 if ($("#favor-shop").is(":visible")) {
			 $.ajax({
                 type: "post",
                 url: "include/zy_function.php",
				 data:{method:"addFavoShop",shop_id:$("#shop-name").attr("rel")},
                 dataType: "json",
                 success: function(){
                	 $("#favor-shop").hide();
            		 $("#un-favor-shop").show();
                 }
              });
			
	     } else {
	    	 $.ajax({
                 type: "post",
                 url: "include/zy_function.php",
				 data:{method:"unFavoShop",shop_id:$("#shop-name").attr("rel")},
                 dataType: "json",
                 success: function(){
                	 $("#un-favor-shop").hide();
        	    	 $("#favor-shop").show();
                 }
              });
	        //add_effect($(".food-action.add, .food-action.book"));
	     }
	});
	$(".add-food").each(function(){
		$(this).click(function(){
			if($("#showOtherCarNotice").html()=="false"){
				showOtherCarNotice();
				return false;
			}
			var shop_id=$("#shop-name").attr("rel");
			var food_id=$(this).attr("food_id");
			var shop_name=$("#shop-name").attr("title");
			var quantity=1;
			var price=$(this).attr("price");
			var food_name=$(this).attr("food_name");
			$.ajax({
                type: "post",
                url: "include/zy_function.php",
				data:{method:"addcart",shop_id:shop_id,shop_name:shop_name,food_id:food_id,food_name:food_name,quantity:quantity,price:price},
                dataType: "json",
                success: function(result){
                	if(result==false){
            			showOtherCarNotice();
            		}else if(result=="add_quantity"){
            			add_effect($(".food-action.add, .food-action.book"));
            			cart_add_quantity(food_id);
                	}
            		else if(result!=null){
            			add_effect($(".food-action.add, .food-action.book"));
            			add_cart_bottom(result);
            			load();
                	}
                }
             });
		});
	});
	//买单时地址更换
	$(".checkout-address-list li").click(function(){
		$(this).each(function(){
			$(this).parent().find("li").each(function(){
				$(this).removeClass("current");
			});
			$(this).addClass("current");
			$(this).children("input").attr("checked","checked");
			if($(this).children("input").attr("value")=="new"){
				$("#address").attr("value","");
				$("#phone").attr("value","");
				$("#tel").attr("value","");
				$("#add_id").attr("value","");
			}else{
				$("#add_id").attr("value",$(this).children("input").attr("value"));
				$(this).children("span").each(function(i){
					if(i==0){
						$("#address").attr("value",$(this).html());
					}
					if(i==1){
						$("#phone").attr("value",$(this).html());
					}
					if(i==2){
						$("#tel").attr("value",$(this).html());
					}
				});
			}
		});
	});
	//买单时的备注信息
	$("#quick-remark span").click(function(){
		if($("#remark").attr("value").indexOf($(this).html())==-1){
			$("#remark-text").attr("value",($("#remark-text").attr("value")+" "+$(this).html()));
			$("#checkout-form #remark").attr("value",$("#remark-text").attr("value"));
		}
	});
	//订单form提交.
	$("#confirm-button-normal").click(function(){
		var address = $("#address").val();
		var phone = $("#phone").val();
            if (address.length > 0) {
                $(".address-row").removeClass("error");
				$(".phone-row").removeClass("error");
				$("#checkout-form #remark").attr("value",$("#remark-text").attr("value"));
				$("#checkout-form").submit();
                return true;
            } else {
                $(".address-row").addClass("error");
                $(".address-row").find(".help-inline").html("请填写正确的送餐地址!");
				$(".phone-row").addClass("error");
                $(".phone-row").find(".help-inline").html("请填写正确的联系电话!");
                return false;
            }
	});
	//购物车里有物品时,设置单品被选中.
	if($("#cart-details").find("tr").size()){
		load();
	}
	//根据category显示食品
	$(".menu-category-filter>ul>li").click(function(){
		$(".menu-category-filter>ul>li").each(function(){
			$(this).removeClass("active");
		});
		$(this).addClass("active");
		var cat_id=$(this).attr("rel");
		if(cat_id=="all"){
			$(".food-category").each(function(){
				$(this).show();
			});
		}else{
			$(".food-category").each(function(){
				if(("food-category-"+cat_id)==$(this).attr("id")){
					$(this).show();
				}else{
					$(this).hide();
				}
			});
		}
	});
	//首页点击餐厅类型,显示餐厅
	$('input[name="filter"]').click(function(){
		var type="";
		$('input[name="filter"]:checked').each(function(i){//遍历每一个名字为interest的复选框，其中选中的执行函数   
			if(i>0){
				type+=" ";
			}
			type+=$(this).attr('value');
			
		});
		if(type==""){
			$(".zyIndexShopList li").each(function(){
					$(this).show();
			});
		}else{
			$(".zyIndexShopList li").each(function(){
				if($(this).hasClass(type)){
					$(this).show();
				}else{
					$(this).hide();
				}
			});
		}
		
	});
	//左侧控制显示
	$(".food-category-selector").click(function(){
		if(!$("#left-tab-cat").is(":hidden")){
			$("#left-tab-cat").hide();
			$("#left-list-cat").show();
		}
	});
	//菜品收藏,鼠标移动上去显示收藏或取消收藏按钮.
	var i=null;
	$(".food-item").live("mouseenter",function() {
		var food_id=$(this).attr("id");
		if ($(this).hasClass("has-favor-icon")) {
				$(this).find(".hover-un-favor-food").show();
		    } else {
		    	$(this).find(".hover-favor-food").show();
		    }
	}).live("mouseleave",function() {
		 $(this).find(".hover-un-favor-food").hide();
    	 $(this).find(".hover-favor-food").hide();
	    clearTimeout(i);
	});
	
	$(".line-one .name span").live("mouseenter",function() {
		var food_id=$(this).parent().parent().parent().attr("id");
		var image_id=food_id.replace("food","image");
		$("#"+image_id).show();
	}).live("mouseleave",function() {
    	 $(this).parent().parent().parent().find(".food_image").hide();
	    clearTimeout(i);
	});
	
	/*$(".food-item").mouseover(function(){
		if ($(this).hasClass("has-favor-icon")) {
			$(this).find(".hover-un-favor-food").show();
	    } else {
	    	$(this).find(".hover-favor-food").show();
	    }
         }).mouseout(function(){
        	 $(this).find(".hover-un-favor-food").hide();
        	 $(this).find(".hover-favor-food").hide();
    });*/
	//单品收藏功能. 添加收藏
	$(".hover-favor-food").click(function(){
		if(show_login_box()){
			return false;
		}
		var add_favor_button=$(this);
		var shop_id=$("#food-"+ $(this).attr("rel"));
		$.ajax({
            type: "post",
            url: "include/zy_function.php",
			data:{method:"addFavoFood",food_id:$(this).attr("rel")},
            dataType: "json",
            success: function(){
            	shop_id.find(".favor-book .favor-icon").show();
        		shop_id.addClass("has-favor-icon");
        		add_favor_button.hide();
        		add_favor_button.next().show();
            }
         });
	});
	//单品收藏功能. 取消收藏
	$(".hover-un-favor-food").click(function(){
		var add_favor_button=$(this);
		var shop_id=$("#food-"+ $(this).attr("rel"));
		$.ajax({
            type: "post",
            url: "include/zy_function.php",
			data:{method:"unFavoFood",food_id:$(this).attr("rel")},
            dataType: "json",
            success: function(){
            	shop_id.find(".favor-book .favor-icon").hide();
        		shop_id.removeClass("has-favor-icon");
        		add_favor_button.hide();
        		add_favor_button.prev().show();
            }
         });
	});
	 document.onclick=function(e){
         var e=e?e:window.event;
         var tar = e.srcElement||e.target;
         if(tar.id!="left-tab-cat"){
        	 if($(tar).attr("class")!="left-category"&&$(tar).attr("class")!="active"){
        		 $("#left-tab-cat").show();
     			 $("#left-list-cat").hide();
        	 } 
         }
         /*if(tar.id!="line-brief"){
        	 if($(tar).attr("class")!="left-category"&&$(tar).attr("class")!="active"){
        		 $("#line-brief").show();
     			 $(".line-detail").hide();
        	 } 
         }*/
       };
});
/**
 * 打开底部购物车
 * @returns {Boolean}
 */
 function openCart() {
    $("#bottom-cart").find(".line-detail").show();
    $(".cart-detail-table").hide();
    $("#bottom-cart").find(".col-group").removeClass("closed active").show();
    $("#col-group-1").addClass("active").show();
    $("#bottom-cart").find(".col-desc").hide();
    $("#bottom-cart").find(".col-add-group").show();
    if ($("#bottom-cart").find(".cart-detail-table").size() <= 1) {
        $("#cart-detail-table-empty").show();
        return true;
    } else {
        $("#cart-detail-table-1").show();
        return true;
    }
};
/**
 * 关闭底部购物车
 */
function close() {
    $("#bottom-cart").find(".line-detail").hide();
    $(".cart-detail-table").hide();
    $("#bottom-cart").find(".col-group").hide();
    $("#bottom-cart").find(".col-add-group").hide();
    $("#bottom-cart").find(".col-desc").show();
    $("#col-group-1").removeClass("active").addClass("closed").show();
};
/**
 * 点单时显示进购物车的箭头图
 * @param b
 */
function add_effect(b) {
    if (typeof b != "undefined") {
        var a = $(window).height() - (b.offset().top - $(window).scrollTop()) - 100;
        if (a < 200) {
            a = 200;
        }
        $("#cart-add-effect").css({
            left: b.offset().left,
            bottom: a
        });
    }
    $("#cart-add-effect").show().animate({
        bottom: "10px",
        opacity: 0
    },
    800,
    function() {
        $("#cart-add-effect").css({
            bottom: "200px",
            opacity: 1,
            display: "none"
        });
    });
}

/**
 * 当购物车有订单时,更换店弹出提示信息.
 * @returns {Boolean}
 */
function showOtherCarNotice(){
    if (2>1) {
    		var i = false;
        	if (!i) {
	            $("#modal-cart-not-the-same-restaurant").modal({
	                keyboard: true,
	                backdrop: "static",
	            });
            i = true;
        	}
        $("#modal-cart-not-the-same-restaurant").modal("show");
        $("#modal-cart-not-the-same-restaurant .btn.clear-cart").click(function() {
            bottom_cart.clear(function() {
                bottom_cart.load(function(j) {
                    $("#topbar-cart-food-num").html("(空)");
                });
            });
            $("#modal-cart-not-the-same-restaurant").modal("hide");
        });
        return false;
    }
    return false;
}
/**
 * 添加购物车里具体每条记录.
 * @param result 根据food_id查询发挥的json数据.
 */
function add_cart_bottom(result){	
	/*var detail="<tr class=\"food-line cart-food-rows\" id=\"bottom-cart-food-"+result.food_id+"\" rel=\""+result.food_id+"\">";
	detail+="<td class=\"name\"><span>"+result.food_name+"</span></td>";
	detail+="<td class=\"price\">￥"+result.price+"</td>";
	detail+="<td class=\"quantity\"><a href=\"javascript:cart_reduce_quantity("+result.food_id+");\" class=\"cart-action cart-decrease\"></a>";
	detail+="<input class=\"order-item  subquantity totalquantity\"  type=\"text\" autocomplete=\"off\" value=\"1\">";
	detail+="<a href=\"javascript:cart_add_quantity("+result.food_id+");\" class=\"cart-action cart-increase\"></a></td>";
	detail+="<td class=\"subtotal cart-subtotal\"  price=\""+result.price+"\">￥"+result.price+"</td>";
	detail+="<td class=\"action\"><a href=\"/cart/delete/group_id/1/entity_id/1273066/parent_entity_id/0\" class=\"cart-action cart-delete\"> </a></td>";
	detail+="</tr>";*/
	$("#cart-details").html(result+$("#cart-details").html());
	
	var total=0,total_quantity=0;
	$(".cart-subtotal").each(function(){
		var subtotal=$(this).html().replace("￥", "");
		total+=parseFloat(subtotal);
	});
	$(".subquantity").each(function(){
		var subtotal=$(this).attr("value");
		if(subtotal>0){
			total_quantity+=parseInt(subtotal,10);
		}
	});
	$("#topbar-cart-food-num").html("("+total_quantity+")");
	$("#col-total").html("共&nbsp;<strong class=\"total-quantity\" id=\"total_quantity\">"+total_quantity+"</strong>&nbsp;份美食&nbsp;|&nbsp;合计&nbsp;<strong class=\"total-price\" id=\"total_price\">"+total.toFixed(2)+"</strong>&nbsp;元 ");
}

/**
 * 所点单品相同时,自动累计加1.
 */
function cart_add_quantity(food_id){
	var quantity=parseInt($("#bottom-cart-food-"+food_id+" .order-item").attr("value"));
	quantity=quantity+1;
	edit_cart_session(food_id,quantity);
	//$("#col-total").html("共&nbsp;<strong class=\"total-quantity\" id=\"total_quantity\">"+$("#cart-details").find("tr").size()+"</strong>&nbsp;份美食&nbsp;|&nbsp;合计&nbsp;<strong class=\"total-price\" id=\"total_price\">"+total.toFixed(2)+"</strong>&nbsp;元 ");
}
/**
 * 单品数量减1.
 */
function cart_reduce_quantity(food_id){
	var quantity=parseInt($("#bottom-cart-food-"+food_id+" .order-item").attr("value"));
	if($("#bottom-cart-food-"+food_id+" .order-item").attr("value")==1){
		event.returnValue = false;
		return false;
	
	}
	quantity=quantity-1;
	edit_cart_session(food_id,quantity);
	//$("#col-total").html("共&nbsp;<strong class=\"total-quantity\" id=\"total_quantity\">"+$("#cart-details").find("tr").size()+"</strong>&nbsp;份美食&nbsp;|&nbsp;合计&nbsp;<strong class=\"total-price\" id=\"total_price\">"+total.toFixed(2)+"</strong>&nbsp;元 ");
}
/**
 * 直接修改单品数量
 */
function cart_quantity_edit(food_id){
	var quantity=parseInt($("#bottom-cart-food-"+food_id+" .order-item").attr("value"));
	edit_cart_session(food_id,quantity);
}
/**
 * 修改session.并计算出小计和合计.在HTML里显示
 * @param food_id
 * @param quantity
 */
function edit_cart_session(food_id,quantity){
	var price=$("#bottom-cart-food-"+food_id+" .cart-subtotal").attr("price");
	$("#bottom-cart-food-"+food_id+" .order-item").attr("value",quantity);
	$("#bottom-cart-food-"+food_id+" .cart-subtotal").html("￥"+(quantity*price).toFixed(2));
	var total=0,total_quantity=0;
	$(".cart-subtotal").each(function(){
		var subtotal=$(this).html().replace("￥", "");
		total+=parseFloat(subtotal);
	});
	$(".subquantity").each(function(){
		var subtotal=$(this).attr("value");
		if(subtotal>0){
			total_quantity+=parseInt(subtotal,10);
		}
	});
	
	$.ajax({
        type: "post",
        url: "include/zy_function.php",
		data:{method:"updatecart",food_id:food_id,quantity:quantity},
        dataType: "json",
        success: function(result){
        	if(result=="success"){
        		$("#total_price").html(total.toFixed(2));
        		$("#total_price_2").html(total.toFixed(2));
        		$("#total_quantity").html(total_quantity);
        		$("#topbar-cart-food-num").html("("+total_quantity+")");
        		$(".total-quantity_2").html(total_quantity);
    		}
        }
     });
}
/**
 * 删除session.并计算出小计和合计.在HTML里显示
 * @param food_id
 * @param quantity
 */
function cart_delete_one(food_id){
	var total=0,total_quantity=0;
	$.ajax({
        type: "post",
        url: "include/zy_function.php",
		data:{method:"deleteOne",food_id:food_id},
        dataType: "json",
        success: function(result){
        	$("#bottom-cart-food-"+food_id).remove();
        	$(".cart-subtotal").each(function(){
        		var subtotal=$(this).html().replace("￥", "");
        		total+=parseFloat(subtotal);
        	});
        	$(".subquantity").each(function(){
        		var subtotal=$(this).attr("value");
        		if(subtotal>0){
        			total_quantity+=parseInt(subtotal,10);
        		}
        	});
        	if(result=="success"){
        		$("#total_price").html(total.toFixed(2));
        		$("#total_price_2").html(total.toFixed(2));
        		$("#col-total").html("共&nbsp;<strong class=\"total-quantity\" id=\"total_quantity\">"+total_quantity+"</strong>&nbsp;份美食&nbsp;|&nbsp;合计&nbsp;<strong class=\"total-price\" id=\"total_price\">"+total.toFixed(2)+"</strong>&nbsp;元 ");
        		$("#topbar-cart-food-num").html("("+total_quantity+")");
        		$("#total_quantity").html(total_quantity);
        		$(".total-quantity_2").html(total_quantity);
        	}else if(result=="none"){
        		//判断这里是店铺页还是订单确认页.如果是订单确认页要发生跳转.
				var url=window.location.href;
				if(url.indexOf('index_shop.php')<0){
					window.location.href="cart_empty.php";
				}
    			$("#total_price").html("0");
        		$("#total_price_2").html("0");
        		$("#col-total").html("");
        		$("#topbar-cart-food-num").html("(空)");
    		}
        }
     });
}
/**
 * 购物车页面打开时,已点餐品默认选中状态
 */
function load(){
    $(".food-item, .image-food-item").removeClass("selected");
    $("#bottom-cart .food-line").each(function(j) {
        var k = $(this).attr("rel");
        $("#food-" + k).addClass("selected");
    });
}

/**
 * 判断用户是否已经登录
 * 如果登录返回用户ID
 * 如果未登录返回0
 */
function user_is_login(){
	if($("#user-id").attr("user_id")>0){
		return $("#user-id").attr("user_id");
	}else{
		return 0;
	}
}
/**
 * 用户未登录时,弹出用户登录框
 */
function show_login_box(){
	if(user_is_login()==0){
		$("#modal-login").modal("show");
		return 1;
	}
}
/**
 * 验证购物车数量,只能是数字
 */
function only_number(dom,food_id){
	var rep=/[^0-9]/g;
	if(rep.test(dom.attr("value"))){
		dom.attr("value","1");
	}
	//修改产品数量
	cart_quantity_edit(food_id);
}
/**
 * 显示选择商圈
 */
function chooseBussiness(){
	$("#modal-bussiness").modal("show");
}
function showCategory (cat_id){
	$.scrollTo("#food-category-"+cat_id,500);
}